package com.py.custom.business.demo.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.py.custom.business.demo.core.mapstruct.BeanConvertUtils;
import com.py.custom.business.demo.core.service.TemplateService;
import com.py.custom.business.demo.core.service.model.TemplatePageDTO;
import com.py.custom.business.demo.protocol.groups.TemplateGroup;
import com.py.custom.business.demo.protocol.request.AddTemplateRequest;
import com.py.custom.business.demo.protocol.request.DelTemplateRequest;
import com.py.custom.business.demo.protocol.request.TemplateRequest;
import com.py.custom.business.demo.protocol.request.UpdateTemplateRequest;
import com.py.custom.data.entity.demo.Template;
import com.py.custom.data.mapper.demo.TemplateDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;

/**
 * description：
 */
@Service
public class TemplateServiceImpl implements TemplateService {

    @Resource
    private TemplateDao templateDao;

    @Autowired
    private BeanConvertUtils beanConvertUtils;

    /**
     * 分页查询
     *
     * @param request
     * @return
     */
    @Override
    public TemplatePageDTO query(TemplateRequest request) {
        // 查询条件
        QueryWrapper<Template> queryWrapper = new QueryWrapper<>();

        // 分页
        Page<Template> page = new Page<>(request.getPageNum(), request.getPageSize());

        // 查询
        Page<Template> templatePage = templateDao.selectPage(page, queryWrapper);

        // 转换
        TemplatePageDTO pageDTO = new TemplatePageDTO();
        pageDTO.setList(beanConvertUtils.template2DtoList(templatePage.getRecords()));
        pageDTO.setTotal(page.getTotal());
        return pageDTO;
    }

    @Override
    @Validated(value = TemplateGroup.SaveGroup.class)
    @Transactional(rollbackFor = Exception.class)
    public boolean addTemplate(AddTemplateRequest request) {
        // 保存模板
        Template template = beanConvertUtils.addTemplateReqCon(request);
        templateDao.insert(template);
        return true;
    }

    @Override
    @Validated(value = TemplateGroup.UpdateGroup.class)
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTemplate(UpdateTemplateRequest request) {
        // 修改模板
        Template template = beanConvertUtils.updateTemplateReqCon(request);
        templateDao.updateById(template);
        return true;
    }

    @Override
    @Validated(value = TemplateGroup.DelGroup.class)
    @Transactional(rollbackFor = Exception.class)
    public boolean delTemplate(DelTemplateRequest request) {
        // 删除模板
        templateDao.deleteById(request.getTemplateId());
        return true;
    }
}
